# 常用api的demo
# 菜鸟教程 https://www.runoob.com/pandas/pandas-tutorial.html
import pandas as pd
import os

# 创建series
def createSeries():
    # 创建Series对象
    print("创建Series对象")
    a = [1, 2, 3]
    series = pd.Series(a)
    print(series)
    print(series[1])

    # 指定索引值 字典形式
    print("指定索引值 字典形式")
    # 通过字典创建series，key为索引值
    a = {"firstVal": "Google", "secVal": "Runoob", "thrVal": "Wiki"}
    series2 = pd.Series(a)
    print(series2)

    # 指定索引值 传入索引 查找对应索引值如果不存在，则会报错
    a = [1, 2, 3]
    series3 = pd.Series(a,index=[2,3,4])
    print(series3)
    print(series3[2])

# 创建DataFrame
def createDataFrame():
    # 通过字典创建
    print("通过字典创建")
    data = {'Site':['Google', 'Runoob', 'Wiki'], 'Age':[10, 12, 13]}
    df = pd.DataFrame(data)
    print(df)

    # 通过列表创建
    print("通过字典创建")
    data2 = [['Google', 10,2], ['Runoob', 12], ['Wiki', 13]]
    df2 = pd.DataFrame(data2, columns=['Site', 'Age',"other"])
    print(df2)
    print(df2['Site'][0])

    # 创建两个Series对象
    series_apples = pd.Series([1, 3, 7, 4])
    series_bananas = pd.Series([2, 6, 3, 5])
    # 将两个Series对象相加，得到DataFrame，并指定列名
    df3 = pd.DataFrame({ 'Apples': series_apples, 'Bananas': series_bananas })
    # 显示DataFrame
    print(df3)
    
# 读csv文件
def readCsv():
    # 读取csv
    path = r'.\file\nba.csv'
    path2 = r'.\file\writeCsv.csv'
    # 返回的是DataFrame对象
    df = pd.read_csv(path2)
    print(df)
    print(type(df))

# 写csv文件 默认为覆盖写
def writeCsv():
    # 写csv文件
    path = r'file\writeCsv.csv'
    nme = ["Google", "Runoob", "Taobao", "Wiki"]
    st = ["www.google.com", "www.runoob.com", "www.taobao.com", "www.wikipedia.org"]
    ag = [90, 40, 80, 98]
    # 字典
    dict = {'name': nme, 'site': st, 'age': ag}
    df = pd.DataFrame(dict)
    # 保存 dataframe index设置为fasle，否则会写入索引
    df.to_csv(path,index=False)
    # mode = 'a' 追加写，header = False不写入列名
    # df.to_csv(path,index=False,header = False,mode='a')

# 读excel
def readExcel():
    path = r"file\test.xlsx"
    # 读取默认的第一个表单
    df = pd.read_excel(path)
    print(df)

    # 读取指定表单的内容（表单名称）
    df = pd.read_excel(path, sheet_name='Sheet1')
    print(df)

    # 读取多个表单，返回一个字典
    dfs = pd.read_excel(path, sheet_name=['Sheet0', 'Sheet1'])
    print(dfs)
    print(dfs['Sheet1'])
    

# 写excel
def writeExcel():
    # 创建一个简单的 DataFrame
    df = pd.DataFrame({
    'Name': ['Alice', 'Bob', 'Charlie'],
    'Age': [25, 30, 35],
    'City': ['New York', 'Los Angeles', 'Chicago']
    })

    # 将 DataFrame 写入 Excel 文件，写入 'Sheet1' 表单
    df.to_excel(r'file\output.xlsx', sheet_name='Sheet1', index=False)

    # 写入多个表单，使用 ExcelWriter
    with pd.ExcelWriter(r'file\output2.xlsx') as writer:
        df.to_excel(writer, sheet_name='Sheet1', index=False)
        df.to_excel(writer, sheet_name='Sheet2', index=False)

# 获取脚本所在目录
script_dir = os.path.dirname(os.path.abspath(__file__))
# 修改当前工作目录
os.chdir(script_dir) 

writeExcel()
